package com.hsgene.order.schedule;

import com.google.common.collect.Lists;
import com.hsgene.common.DeleteFlagType;
import com.hsgene.common.util.date.SimpleDateUtils;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.order.condition.GeneticTestingOrderCondition;
import com.hsgene.order.constants.v1.OrderStatus;
import com.hsgene.order.domain.v1.GeneticTestingOrder;
import com.hsgene.order.persistence.OrderRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单模块定时任务
 * 已废弃：修改实现方式，采用RocketMQ延迟消息来实现商城订单自动收货功能
 * 详情见：{@link com.hsgene.order.listener.OrderAutoReceiptListener}
 *
 * @author wangbing
 * @version 1.0, 2018/11/14
 */
// @Component
@Deprecated
public class OrderScheduler {

    private final static Logger LOGGER = LoggerFactory.getLogger(OrderScheduler.class);

    @Resource
    private OrderRepository orderRepository;

    @Value("${genetic.testing.orders.receipt.limit}")
    private Integer ordersReceiptLimit;

    /**
     * 发货时间超过期限的订单自动转为已收货，即转到待评价状态
     * 定时任务每5分钟执行一次
     */
    // @Scheduled(cron = "0 */1 * * * ?")
    @Deprecated
    public void autoConfirmReceipt() {
        GeneticTestingOrderCondition condition = new GeneticTestingOrderCondition();
        condition.setDeleteFlag(DeleteFlagType.NOT_DELETED.getCode());
        condition.setStatus(String.valueOf(OrderStatus.WAIT_RECEIPT_GOODS.getCode()));
        LimitHelper limitHelper = LimitHelper.create(1, Integer.MAX_VALUE, false);
        LOGGER.info("自动确认收货定时任务：开始执行");
        List<GeneticTestingOrder> orders = orderRepository.queryOrders(condition, null, limitHelper);
        List<GeneticTestingOrder> updates = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(orders)) {
            updates = orders.stream()
                    .filter(this::isBeyondReceiptLimit)
                    .peek(order -> {
                        Date now = new Date();
                        order.setStatus(OrderStatus.WAIT_COMMENT.getCode());
                        order.setReceiveDateTime(now);
                        order.setUpdateDateTime(now);
                        orderRepository.updateOrderReceipt(order);
                    }).collect(Collectors.toList());
        }
        StringBuilder updateDesc = new StringBuilder("自动确认收货定时任务：执行完毕。");
        if (CollectionUtils.isEmpty(updates)) {
            updateDesc.append("没有满足自动确认的订单");
        } else {
            updates.stream()
                    .map(GeneticTestingOrder::getOrderNo)
                    .reduce((a, b) -> a + "," + b)
                    .ifPresent(e -> {
                        updateDesc.append("已对订单[");
                        updateDesc.append(e);
                        updateDesc.append("]进行自动确认收货操作");
                    });
        }
        LOGGER.info(updateDesc.toString());
    }

    /**
     * 是否超过限制
     *
     * @param order 订单信息
     * @return true：超过收货期限；false：没有超过收货期限
     */
    private boolean isBeyondReceiptLimit(GeneticTestingOrder order) {
        Date deliveryDateTime = order.getDeliveryDateTime();
        if (deliveryDateTime == null) {
            LOGGER.error("待收货订单[{}]的发货时间[delivery_date_time]为空，无法判断是否超过自动转换期限", order.getOrderNo());
            return false;
        }
        LocalDateTime createDateTime = LocalDateTime.ofInstant(deliveryDateTime.toInstant(), ZoneId
                .systemDefault());
        int durationDays = SimpleDateUtils.durationDays(createDateTime, LocalDateTime.now());

        return durationDays > ordersReceiptLimit;
    }
}
